import React, { createContext, useState, useEffect, useRef } from 'react';
import { Toast } from 'antd-mobile'
import { List } from 'react-vant'
import HeadTop from '@/components/HeadTop';
import ListItem from '../_parts/ListItem';
import ModalSpare from '../_parts/ModalSpare';
import { validatenull } from "@/utils/validate";
import { dateTimeFormatter } from "@/utils/utils";
import { listFieldsDetail } from '../_parts/const';
import ApiIndex from '@/api/index'
import "./index.less"
import { connect } from 'react-redux';
import { MyContext } from '@/context/index';
const { Provider, Consumer } = MyContext

function Index(props) {
    const [inputVal, setInputVal] = useState('');
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [finished, setFinished] = useState(false);
    const [pageIndex, setPageIndex] = useState(1);
    const { history } = props
    const ModalSpareRef = useRef(null)
    const [ListRow, setListRow] = useState({});
    const [totalObj,setTotalObj] = useState({})

    useEffect(()=>{
        getTotal()
    },[])

    const getTotal = ()=>{
        ApiIndex.getInventoryNumber({ no: props.location.state.no}).then( res=>{
            if(res.data.code == 0){
                setTotalObj(res.data.data)
            }else{
                setTotalObj({})
            }
        })
    }

    const getList = async (pageNum) => {
        setLoading(true);
        if (loading) return
        let params = {
            no: props.location.state.no,
            page: pageNum ? 1 : pageIndex,
            size: 10,
        }
        ApiIndex.checkComplet(params).then(res => {
            setLoading(false);
            if (res.data.code === 0) {
                let _data = res.data.data.records || []
                setList((prevList) => [...prevList, ..._data]);
                // 判断是否还有更多数据
                if (_data.length < 10) {
                    setFinished(true);
                } else {
                    setPageIndex((prevIndex) => prevIndex + 1);
                }
            } else {
                setFinished(true);
            }
        })
    }

    const getRow = (row) => {
        let prmlist = []
        ListRow.inventoryQty = row.sendNum
        prmlist.push(ListRow)

        let params = {
            no: props.location.state.no,
            itemList: prmlist,
            updateUser: props.username,
            updateTime: dateTimeFormatter(new Date(), 'yyyy-MM-dd hh:mm:ss')
        }
        ApiIndex.confirmInventory(params).then(res => {
            if (!res.data.code) {
                setLoading(true)
                setList([])
                setLoading(false)
                setPageIndex(1)
                getList(1)
                Toast.show({
                    content: '盘点成功'
                })
                setInputVal('')
                
                getTotal()
            } else {
                Toast.show({
                    content: res.data.msg || '盘点失败'
                })
            }
            ModalSpareRef.current.setVisible(false)
        })
    }

    // 搜索
    const sendHandlePressVal = (value) => {
        if (validatenull(value)) return
        setInputVal(value)
        let _value = value.trim()
        if (value.indexOf("*") != -1) {
            _value = value.split("*")[0]
        }

        ApiIndex.getByRecordNoAndToolCode({ recordNo: props.location.state.no, toolCode: _value }).then(res => {
            if (!res.data.code) {
                setListRow(res.data.data)
                ModalSpareRef.current.setVisible(true)

            } else {
                Toast.show({
                    content: '扫描的条码，不是盘点明细的条码'
                })
            }
        })
    }

    const checkItem = () => {
        ApiIndex.checkComplet({
            no: props.location.state.no
        }).then(res => {

            Toast.show({
                content: res.data.msg || '校验失败'
            })
        })
    }

    return (
        <div className='page-wrapper return-page'>
            <Provider value={{ placeholderTxt: "请扫描备件条码", inputVal: inputVal }}>
                <HeadTop
                    title="扫码盘点"
                    history={history}
                    search={true}
                    sendHandlePressVal={sendHandlePressVal}
                ></HeadTop>
            </Provider>
            <div className="body-no">
                <span>盘点编号：{props.location.state.no}</span>
                <span>盘点名称：{props.location.state.name}</span>
            </div>
            <div className="body-no">
                <span>备件种类：{totalObj.toolTypeSum}</span>
                <span>已盘备件种类：{totalObj.toolTypeCount}</span>
            </div>
            <div className="page-body" style={{ padding: 15 }}>
                {/* {
                    List.length > 0 ?
                        List.map(el => <ListItem
                            key={el.id}
                            item={el}
                            history={history}
                            listFields={listFieldsDetail}
                        ></ListItem>)
                        : <div className='no-list-data'>
                            无更多数据
                        </div>
                } */}
                <List finished={finished} errorText='请求失败，点击重新加载' onLoad={getList}>
                    {
                        list.map(el => <ListItem
                            key={el.id}
                            item={el}
                            history={history}
                            listFields={listFieldsDetail}
                        ></ListItem>)
                    }
                    {finished ? <div className='loadingTxt'>无更多数据</div> : null}
                </List>

            </div>
            <ModalSpare ref={ModalSpareRef} type="return" modalTitle="扫码盘点" ListRow={ListRow} getRow={getRow}></ModalSpare>
        </div>
    );
}


const mapStateToProps = (state) => {
    return {
        username: state.username
    };
};
export default connect(mapStateToProps)(Index);


